package com.chatplus.application.web.util;

import org.springframework.context.ApplicationContext;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.context.support.WebApplicationContextUtils;

public final class WebApplicationContextHolder {

    private WebApplicationContextHolder() {
        throw new IllegalStateException();
    }

    private static ApplicationContext applicationContext;

    public static <T> T getBean(Class<T> clz) {
        return getApplicationContext().getBean(clz);
    }

    public static ApplicationContext getApplicationContext() {
        if (applicationContext == null) {
            ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            if (requestAttributes != null) {
                applicationContext = WebApplicationContextUtils.getWebApplicationContext(requestAttributes.getRequest().getServletContext());
            } else {
                throw new NullPointerException("请在web环境中使用！");
            }
        }
        return applicationContext;
    }
}
